package com.cqjtu.store.order.service.impl;

import com.cqjtu.store.address.mapper.AddressMapper;
import com.cqjtu.store.address.pojo.entity.Address;
import com.cqjtu.store.common.PageDTO;
import com.cqjtu.store.common.PageVO;
import com.cqjtu.store.common.ServiceCode;
import com.cqjtu.store.common.ServiceException;
import com.cqjtu.store.order.mapper.OrderMapper;
import com.cqjtu.store.order.pojo.DTO.OrderPageDTO;
import com.cqjtu.store.order.pojo.DTO.SetOrderDTO;
import com.cqjtu.store.order.pojo.DTO.TimeDTO;
import com.cqjtu.store.order.pojo.entity.Order;
import com.cqjtu.store.order.pojo.vo.*;
import com.cqjtu.store.order.service.OrderService;
import com.cqjtu.store.product.mapper.ProductMapper;
import com.cqjtu.store.product.pojo.entity.Product;
import com.cqjtu.store.user.mapper.UserMapper;
import com.cqjtu.store.user.pojo.entity.User;
import com.cqjtu.store.user.pojo.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UserMapper userMapper;
    @Override
    public List<OrderVO> getList(UserLoginVO userLoginVO) {
        List<OrderVO> orderList = orderMapper.getOrderList(userLoginVO.getId());
        if(orderList == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"");
        }
        return orderList;
    }

    @Override
    public List<OrderVO> getListByStatus(Integer status, UserLoginVO userLoginVO) {
        List<OrderVO> orderList = orderMapper.getOrderListByStatus(status,userLoginVO.getId());
        if(orderList == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"此用户没有订单数据");
        }
        //todo 获取订单总金额
        return orderList;
    }

    @Override
    public SetOrderVO insertOrder(SetOrderDTO setOrderDTO, UserLoginVO userLoginVO) {
        Address address=addressMapper.getById(setOrderDTO.getAddressId());
        Product product=productMapper.getProductById(setOrderDTO.getProId());
        if (address==null){
            new ServiceException(ServiceCode.ERR_EXISTS,"该用户地址不存在");
        }
        if (product==null){
            new ServiceException(ServiceCode.ERR_EXISTS,"该商品不存在");
        }
        Order order=new Order();
        order.setUserId(userLoginVO.getId());
        order.setRecvName(address.getName());
        order.setRecvPhone(address.getPhone());
        order.setRecvProvince(address.getProvinceName());
        order.setRecvCity(address.getCityName());
        order.setRecvArea(address.getAreaName());
        order.setRecvAddress(address.getAddress());
        order.setStatus(1);
        order.setTotalPrice(product.getPrice()*setOrderDTO.getNum());
        Date date=new Date();
        order.setOrderTime(date);
        order.setIsDelete(0);
        order.setCreatedUser(userLoginVO.getUsername());
        order.setCreatedTime(date);
        order.setModifiedUser(userLoginVO.getUsername());
        order.setModifiedTime(date);
        boolean ok=orderMapper.createOrder(order);


        return null;
    }

    /**
     * 实时获取订单数据
     * @return
     */
    @Override
    public int getRealTimeNum() {
        Date date = new Date();
        System.out.println(date);
        int res = orderMapper.getRealTimeNum(date);
        return res;
    }

    /**
     * 获取某个时间端内的订单数量
     * @param timeDTO
     * @return
     * @throws ParseException
     */
    @Override
    public List<OrderTotalVO> getTotalInTime(TimeDTO timeDTO){
//        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        System.out.println(timeDTO.getEnd());
        List<OrderTotalVO> orderTotalVOList = new ArrayList<>();
        long startTime = timeDTO.getStart().getTime();
        long endTime = timeDTO.getEnd().getTime();
//        System.out.println(startTime);
//        System.out.println(endTime);
        long day=86400000;
//        timeDTO.setStart(new Date(startTime+day));
        for (long i = startTime; i <=endTime ; i+=day) {
            Date date = new Date(i);
            int res = orderMapper.getNumByDay(date);
            OrderTotalVO orderTotalVO = new OrderTotalVO();
            orderTotalVO.setDate(date);
            orderTotalVO.setNum(res);
            orderTotalVOList.add(orderTotalVO);
        }
        System.out.println(orderTotalVOList);
        return orderTotalVOList;
    }

    @Override
    public List<OrderTotalVO> getUserAndProductOrder(Integer userId,Integer productId) {
        List<OrderTotalVO> orderTotalVOList = new ArrayList<>();
        //获取用户的最早的订单
//        OrderVO orderVO = orderMapper.getEarliest(id);
        User user = userMapper.getUserById(userId);
        if(Objects.isNull(user)){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该用户不存在");
        }
        Product product = productMapper.getProductById(productId);
        if(Objects.isNull(product)){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该产品不存在");
        }
        long start = user.getCreatedTime().getTime();
        long now = new Date().getTime();
        long day=86400000;
        start = start - start%day - 28800000;
        if(now%day!=0) now=now-now%day- 28800000;
        for (long i = start; i <= now ; i+=day) {
            Date date = new Date(i);
            OrderTotalVO orderTotalVO = new OrderTotalVO();
            orderTotalVO.setDate(date);
            orderTotalVO.setNum(orderMapper.getNumByDayAndUserProduct(date,userId,productId));
            orderTotalVOList.add(orderTotalVO);
        }
        return orderTotalVOList;
    }

    @Override
    public List<OrderTotalVO> getProductOrder(Integer productId) {
        List<OrderTotalVO> orderTotalVOList = new ArrayList<>();
        Product product = productMapper.getProductById(productId);
        if(Objects.isNull(product)){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该产品不存在");
        }
        long start = product.getCreatedTime().getTime();
        long now = new Date().getTime();
        long day=86400000;
        start = start - start%day - 28800000;
        for (long i = start; i <= now ; i+=day) {
            Date date = new Date(i);
            OrderTotalVO orderTotalVO = new OrderTotalVO();
            orderTotalVO.setDate(date);
            orderTotalVO.setNum(orderMapper.getNumByDayAndProduct(date,productId));
            orderTotalVOList.add(orderTotalVO);
        }

        return orderTotalVOList;
    }

    @Override
    public List<OrderTotalVO> getUserOrder(Integer userId) {
        List<OrderTotalVO> orderTotalVOList = new ArrayList<>();
        User user = userMapper.getUserById(userId);
        if(Objects.isNull(user)){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该用户不存在");
        }
        long start = user.getCreatedTime().getTime();
        long now = new Date().getTime();
        long day=86400000;
        start = start - start%day - 28800000;
        if(now%day!=0) now=now-now%day- 28800000;
        for (long i = start; i <= now ; i+=day) {
            Date date = new Date(i);
            OrderTotalVO orderTotalVO = new OrderTotalVO();
            orderTotalVO.setDate(date);
            orderTotalVO.setNum(orderMapper.getNumByDayAndUser(date,userId));
            orderTotalVOList.add(orderTotalVO);
        }
        return orderTotalVOList;
    }

    /**
     * 后台系统获取所有订单信息
     * @return pageDTO
     */
    @Override
    public PageVO<List<OrderListVO>> getAllOrder(PageDTO pageDTO) {
        List<OrderListVO> orderListVOList = orderMapper.getAllOrder(pageDTO);
        int count = orderMapper.getAllOrderNum();
        PageVO<List<OrderListVO>> pageVO = new PageVO<>(pageDTO.getPageIndex(), pageDTO.getPageSize(),count,orderListVOList);
        return pageVO;
    }

    /**
     * 后台系统根据关键字查询订单
     * @param pageDTO
     * @return
     */
    @Override
    public PageVO<List<OrderListVO>>getOrderByKey(OrderPageDTO pageDTO) {
        List<OrderListVO> orderListVOList = orderMapper.getOrderByKey(pageDTO);
        int count = orderMapper.getKeyOrderNum(pageDTO.getKey());
        PageVO<List<OrderListVO>> pageVO = new PageVO<>(pageDTO.getPageIndex(), pageDTO.getPageSize(),count,orderListVOList);
        return pageVO;
    }

    /**
     * 后台删除用户的订单
     * @param id
     */
    @Override
    public void deleteOrder(Integer id) {
        //删除订单项
        int result =  orderMapper.deleteOrderItems(id);
        if(result==0){
            throw new ServiceException(ServiceCode.ERR_DELETE_FAILED,"订单项删除失败");
        }
        //删除订单
        result = orderMapper.deleteOrder(id);
        if(result==0){
            throw new ServiceException(ServiceCode.ERR_DELETE_FAILED,"订单删除失败");
        }

    }

    @Override
    public int getAllOrderNum() {
        int num = orderMapper.getAllOrderNum();
        return num;
    }
}
